// 实现这个项目的构建任务
const { src, dest, parallel, series, watch} = require('gulp')

const loadPlugins = require('gulp-load-plugins');

const plugins = loadPlugins();
const sass = require('gulp-sass')(require('sass'));
const del = require('del')
const browserSync = require('browser-sync')

const bs = browserSync.create()// 开发服务器
/**
 *
 * @returns
 */
const clean = () => {
  return del(['dist'])
}
const style  = () => {
    return src('src/assets/styles/*.scss', { base: 'src'})
           .pipe(sass())
           .pipe(dest('dist'))
}

const script = () => {
    return src('src/assets/scripts/*.js', {base: 'src'})
           .pipe(plugins.babel({ presets: ['@babel/preset-env']})) // 唤醒babel/core的转换过程。
           .pipe(dest('dist'))
}

const page = () => {
    // return src('src/**/*.html') // 任意子目录下的html文件
    return src('src/*.html')
           .pipe(plugins.swig())
           .pipe(dest('dist'))
}

/**
 * 通过gulp的imagemin插件来压缩图片和字体的大小
 */
 const image = () => {
    return src('src/assets/image/**', { base: 'src'})
           .pipe(plugins.imagemin())
           .pipe(dest('dist'))
  }

  const font = () => {
    return src('src/assets/fonts/**', { base: 'src'})
           .pipe(plugins.imagemin())
           .pipe(dest('dist'))
  }

  const extra = () => {
    return src('public/**', { base: 'src'})
           .pipe(dest('dist'))
  }

  const serve = () => {
     watch('src/assets/styles/*.scss', style)
     watch('src/assets/scripts/*.js', script)
     watch('src/*.html', page)
     watch([
      'src/assets/image/**',
      'src/assets/fonts/**',
      'public/**'
     ], bs.reload)
     bs.init({
       notify: false,
       port: 8020,
       files: 'dist/**', // 这些文件发生改变后刷新浏览器
       server: {
         baseDir: 'dist',
         routes: {
           '/node_modules': 'node_modules'
         }
       }
     })
  }

  const useref = () => {
    return src('dist/*.html', {base: 'dist'})
           .pipe(plugins.useref({ searchPath: ['dist', '.']}))
           .pipe(plugins.if(/\.js$/, plugins.uglify()))
           .pipe(plugins.if(/\.css$/, plugins.cleanCss()))
           .pipe(plugins.if(/\.html$/, plugins.htmlmin({ collapseWhitespace: true, minifyCss: true, minifyJs: true})))
           .pipe(dest('release'))
  }

const compile = parallel(style,script,page)
// 上线之前用到的
const build = series(clean,parallel(compile, image, font,extra))
const develop = series(compile, serve)


// 使用任务需要导出
module.exports = {
    compile,
    build,
    develop,
    useref
}
